package com.hgkj.cloud.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hgkj.cloud.base.common.PageInfo;
import com.hgkj.cloud.base.dao.TenantTableReportsAttachedMapper;
import com.hgkj.cloud.base.dao.TenantTableReportsMapper;
import com.hgkj.cloud.base.dao.TenantTableTaskInfoMapper;
import com.hgkj.cloud.base.dao.TenantTableTasksMapper;
import com.hgkj.cloud.base.domain.TenantTableReports;
import com.hgkj.cloud.base.domain.TenantTableReportsAttached;
import com.hgkj.cloud.base.domain.TenantTableTaskInfo;
import com.hgkj.cloud.base.domain.TenantTableTasks;
import com.hgkj.cloud.base.enums.OptionEnum;
import com.hgkj.cloud.base.service.TenantTableTaskInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TenantTableTaskInfoServiceImpl implements TenantTableTaskInfoService {

    @Autowired
    private TenantTableTaskInfoMapper tenantTableTaskInfoMapper;

    @Resource
    private TenantTableTasksMapper tenantTableTasksMapper;

    @Resource
    private TenantTableReportsMapper tenantTableReportsMapper;

    @Resource
    private TenantTableReportsAttachedMapper attachedMapper;

    @Resource
    private TenantTableTaskInfoMapper infoMapper;

    private static final String UPPER_TOTAL = "upperTotal";
    private static final String UNDER_TOTAL = "underTotal";
    private static final String CONTENT = "content";
    private static final String REPORT_LEVEL = "reportLevel";
    private static final String ENABLED = "enabled";

    @Override
    public int deleteByPrimaryKey(String uuid) {
        return tenantTableTaskInfoMapper.deleteByPrimaryKey(uuid);
    }

    @Override
    public int insert(TenantTableTaskInfo record) {
        return tenantTableTaskInfoMapper.insert(record);
    }

    @Override
    public int insertSelective(TenantTableTaskInfo record) {
        return tenantTableTaskInfoMapper.insertSelective(record);
    }

    @Override
    public TenantTableTaskInfo selectByPrimaryKey(String uuid) {
        return tenantTableTaskInfoMapper.selectByPrimaryKey(uuid);
    }

    @Override
    public TenantTableTaskInfo selectTaskInfoByMap(Map<String, Object> map){
        return tenantTableTaskInfoMapper.selectTaskInfoByMap(map);
    }

    @Override
    public int updateByPrimaryKeySelective(TenantTableTaskInfo record) {
        return tenantTableTaskInfoMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(TenantTableTaskInfo record) {
        return tenantTableTaskInfoMapper.updateByPrimaryKey(record);
    }

    @Override
    public int deleteTableTaskInfo(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.deleteTableTaskInfo(map);
    }

    @Override
    public List<TenantTableTaskInfo> listTableTaskInfoByTaskUuid(String task_uuid) {
        return tenantTableTaskInfoMapper.listTableTaskInfoByTaskUuid(task_uuid);
    }

    @Override
    public List<TenantTableTaskInfo> findFinishedTableTask(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.findFinishedTableTask(map);
    }

    @Override
    public List<TenantTableTaskInfo> listUserFinishedTaskInfos(PageInfo pi, Map<String, Object> map) {
        if(pi != null){
            map.put("currentCount", pi.getCurrentCount());
            map.put("pageSize", pi.getPageSize());
        }
        return tenantTableTaskInfoMapper.listUserFinishedTaskInfos(map);
    }

    @Override
    public List<Map<String, Object>> listPageTableTaskInfos(PageInfo pi, Map<String, Object> map) {
        if(pi != null){
            map.put("currentCount", pi.getCurrentCount());
            map.put("pageSize", pi.getPageSize());
        }
        return tenantTableTaskInfoMapper.listPageTableTaskInfos(map);
    }

    @Override
    public int listPageTableTaskInfosCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listPageTableTaskInfosCount(map);
    }

    @Override
    public List<Map<String, Object>> listAllTableTaskInfos(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listAllTableTaskInfos(map);
    }

    @Override
    public List<TenantTableTaskInfo> listCheckTableTaskInfos(String task_uuid) {
        return tenantTableTaskInfoMapper.listCheckTableTaskInfos(task_uuid);
    }

    @Override
    public List<TenantTableTaskInfo> getTableTaskInfo(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getTableTaskInfo(map);
    }

    @Override
    public int countTestUsers(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.countTestUsers(map);
    }

    @Override
    public int countTaskFinishedUsers(String task_uuid) {
        return tenantTableTaskInfoMapper.countTaskFinishedUsers(task_uuid);
    }

    @Override
    public List<Map<String, Object>> selectCountWarningUsers(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.selectCountWarningUsers(map);
    }

    @Override
    public List<Map<String, Object>> listTableFactorUser(PageInfo pi, Map<String, Object> map) {
        if(pi != null){
            map.put("currentCount", pi.getCurrentCount());
            map.put("pageSize", pi.getPageSize());
        }
        return tenantTableTaskInfoMapper.listTableFactorUser(map);
    }

    @Override
    public int listTableFactorUserCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listTableFactorUserCount(map);
    }

    @Override
    public List<String> listTableFactorValues(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listTableFactorValues(map);
    }

    @Override
    public int listTableFactorCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listTableFactorCount(map);
    }

    @Override
    public List<Map<String, Object>> listTableAnazyleCounts(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listTableAnazyleCounts(map);
    }

    @Override
    public List<Map<String, Object>> listTableAnazyleCountsByMap(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listTableAnazyleCountsByMap(map);
    }

    @Override
    public List<Map<String, Object>> listTableAnazyleFactorUser(PageInfo pi, Map<String, Object> map) {
        if(pi != null){
            map.put("currentCount", pi.getCurrentCount());
            map.put("pageSize", pi.getPageSize());
        }
        return tenantTableTaskInfoMapper.listTableAnazyleFactorUser(map);
    }

    @Override
    public int countListTableAnazyleFactorUser(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.countListTableAnazyleFactorUser(map);
    }

    @Override
    public List<Map<String, Object>> listTableAnazyleFactorUserByMap(PageInfo pi, Map<String, Object> map) {
        if(pi != null){
            map.put("currentCount", pi.getCurrentCount());
            map.put("pageSize", pi.getPageSize());
        }
        return tenantTableTaskInfoMapper.listTableAnazyleFactorUserByMap(map);
    }

    @Override
    public int countListTableAnazyleFactorUserByMap(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.countListTableAnazyleFactorUserByMap(map);
    }

    @Override
    public List<Map> getCommitSuicidePeople(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getCommitSuicidePeople(map);
    }

    @Override
    public Map<String,Object> getPoliceStressGender(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getPoliceStressGender(map);
    }

    @Override
    public List<Map<String, Object>> getPoliceStressGenderUsers(PageInfo pi,Map<String, Object> map) {
        if(pi != null){
            map.put("currentCount", pi.getCurrentCount());
            map.put("pageSize", pi.getPageSize());
        }
        return tenantTableTaskInfoMapper.getPoliceStressGenderUsers(map);
    }

    @Override
    public Long getPoliceStressGenderUsersCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getPoliceStressGenderUsersCount(map);
    }

    @Override
    public List<Map> getPoliceStressTenant(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getPoliceStressTenant(map);
    }

    @Override
    public List<Map> getPoliceStressTime(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getPoliceStressTime(map);
    }

    /**
     * 获取用户参加的测评任务数
     * @param map
     * @return
     */
    @Override
    public Long getUserTask(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getUserTask(map);
    }

    /**
     * 获取用户参加的测评任务总量表数
     * @param map
     * @return
     */
    @Override
    public  Map<String,Long> getUserTaskInfo(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getUserTaskInfo(map);
    }

    @Override
    public Page<HashMap<String, Object>> listPageTableTaskInfos(Integer pageNum, Integer PageSize, Map<String, Object> map) {
        PageHelper.startPage(pageNum,PageSize);
        return tenantTableTaskInfoMapper.listPageTableTaskInfoss(map);
    }

    @Override
    public TenantTableTaskInfo findTableTaskInfoByUuid(String uuid) {
        return tenantTableTaskInfoMapper.findTableTaskInfoByUuid(uuid);
    }

    @Override
    public List<Map>  listAllTableTaskInfosCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.listAllTableTaskInfosCount(map);
    }

    @Override
    public void updateTaskInfoToChongzhi(String uuid) {
        tenantTableTaskInfoMapper.updateTaskInfoToChongzhi(uuid);
    }

    @Override
    public Map<String, Object> statAllJoinTableTaskInfoRate(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.statAllJoinTableTaskInfoRate(map);
    }

    @Override
    public Map<String, Object> statMonthTableTaskInfo(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.statMonthTableTaskInfo(map);
    }

    @Override
    public int statTableTaskInfoCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.statTableTaskInfoCount(map);
    }

    @Override
    public List<Map<String, Object>> statTenFactorWarning(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.statTenFactorWarning(map);
    }

    @Override
    public int getUserTaskInfoFinishedCount(Map<String, Object> map) {
        return tenantTableTaskInfoMapper.getUserTaskInfoFinishedCount(map);
    }

    @Override
    public List<Map<String, Object>> listExcptionTableTaskInfos() {
        return tenantTableTaskInfoMapper.listExcptionTableTaskInfos();
    }

    @Override
    public List<Map<String, Object>> listExcptionTableTasks() {
        return tenantTableTaskInfoMapper.listExcptionTableTasks();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTasksInfoAndReports(String userUuid, String frameworkId, String value, String times, String taskInfoUuid) {

        TenantTableTaskInfo tableTaskInfo = infoMapper.selectByPrimaryKey(taskInfoUuid);
        if (null == tableTaskInfo) {
            throw new RuntimeException("未找到当前任务信息！");
        }

        //修改任务信息表 保存答案集合以及时间
        TenantTableTaskInfo info = new TenantTableTaskInfo();
        info.setUuid(taskInfoUuid);
        info.setAnswer(value);
        info.setAnswer_seconds(times);
        String[] split = times.split("\\|");
        int answerSeconds = 0;
        for (String time : split) {
            answerSeconds = answerSeconds + (Integer.parseInt(time));
        }
        info.setAnswer_time(answerSeconds);
        infoMapper.updateByPrimaryKey(info);

        //根据规则计算结果
        Map<String, Object> map = calculationResults(value);
        //保存测评报告表
        TenantTableReports tenantTableReports = new TenantTableReports();
        tenantTableReports.setTask_info_uuid(taskInfoUuid);
        tenantTableReports.setReport_level((String) map.get(REPORT_LEVEL));
        tenantTableReports.setReport_prompt((String) map.get(CONTENT));
        tenantTableReports.setDate(System.currentTimeMillis());
        tenantTableReports.setEnabled((Integer) map.get(ENABLED));
        tenantTableReports.setTable_uuid(tableTaskInfo.getTable_uuid());
        tenantTableReports.setIs_done(0);
        tenantTableReports.setUser_uuid(userUuid);
        tenantTableReportsMapper.insert(tenantTableReports);

        //保存测试报告
        TenantTableReportsAttached attached = new TenantTableReportsAttached();
        attached.setTaskInfoUuid(taskInfoUuid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("answer_a", map.get(CONTENT));
        Integer upperTotal = (Integer) map.get(UPPER_TOTAL);
        Integer underTotal = (Integer) map.get(UNDER_TOTAL);
        jsonObject.put("total_o", (upperTotal + underTotal));
        attached.setFactorJson(jsonObject.toJSONString());
        attached.setEnabled(1);
        attachedMapper.insert(attached);

        //最后修改任务
        TenantTableTasks tenantTableTasks = tenantTableTasksMapper.selectByPrimaryKey(tableTaskInfo.getTask_uuid());
        if (null == tenantTableTasks) {
            throw new RuntimeException("未找到测评任务表！");
        }
        if (tenantTableTasks.getUser_num() == tenantTableTasks.getFinish_num() + 1) {
            tenantTableTasks.setStatus(3);
        }
        tenantTableTasks.setFinish_num(tenantTableTasks.getFinish_num() + 1);
        tenantTableTasksMapper.updateByPrimaryKey(tenantTableTasks);
    }

    private Map<String, Object> calculationResults(String answer) {
        Map<String, Object> map = new HashMap<>();
        String[] split = answer.split("\\|");
        int upperTotal = 0;
        int underTotal = 0;
        String content = "";
        String reportLevel = "";

        //计算前半部分总分
        for (int i = 0; i < 9; i++) {
            //计算前半部分总分
            //System.out.println("第" + (i + 1) + "题得分为：" + OptionEnum.toEnum(split[i], true));
            upperTotal = upperTotal + OptionEnum.toEnum(split[i], true);
        }

        //计算后半部分总分
        for (int i = 9; i < split.length; i++) {
            //计算后半部分总分
            underTotal = underTotal + OptionEnum.toEnum(split[i], true);
        }
        if (OptionEnum.toEnum(split[12], false) == 1) {
            map.put(ENABLED, 0);
            content = content + "[问卷结果存疑]";
        } else {
            map.put(ENABLED, 1);
        }
        if (upperTotal >= 15 && OptionEnum.toEnum(split[8], true) > 1) {
            content = content + "[严重心理危机]";
        } else if (upperTotal >= 10 && OptionEnum.toEnum(split[8], true) > 1) {
            content = content + "[一般心理危机]";
        }


        /**
         * 项目9代表有自伤意念，是核心症状，如果得分>1，则为阳性
         * 另外，项目1、4，代表着抑郁的核心症状，得分>1（即选择2、3），需要关注，对于进一步访谈可供借鉴，但基于前期试测统计，暂不列入评判指标内
         */
        if (OptionEnum.toEnum(split[8], true) > 1) {
            content = content + "核心症状为阳性。";
        }
        if (OptionEnum.toEnum(split[0], true) > 1 || OptionEnum.toEnum(split[3], true) > 1) {
            content = content + "需要关注，对于进一步访谈可供借鉴，但基于前期试测统计，暂不列入评判指标内。";
        }
        /**
         *
         * 0-4 　没有抑郁症　  　（注意自我保重）
         * 5-9 　可能有轻微抑郁症 (建议咨询心理医生或心理医学工作者)
         * 10-14 可能有中度抑郁症 (最好咨询心理医生或心理医学工作者)
         * 15-19 可能有中重度抑郁症(建议咨询心理医生或精神科医生)
         * 20-27 可能有重度抑郁症　(一定要看心理医生或精神科医生)
         */
        if (upperTotal >= 0 && upperTotal <= 4) {
            reportLevel = "0";
            content = content + "没有抑郁症（注意自我保重）。";
        } else if (upperTotal >= 5 && upperTotal <= 9) {
            reportLevel = "1";
            content = content + "可能有轻微抑郁症 (建议咨询心理医生或心理医学工作者)。";
        } else if (upperTotal >= 10 && upperTotal <= 14) {
            reportLevel = "2";
            content = content + "可能有中度抑郁症 (最好咨询心理医生或心理医学工作者)。";
        } else if (upperTotal >= 15 && upperTotal <= 19) {
            reportLevel = "3";
            content = content + "可能有中重度抑郁症(建议咨询心理医生或精神科医生)。";
        } else if (upperTotal >= 20 && upperTotal <= 27) {
            reportLevel = "4";
            content = content + "可能有重度抑郁症　(一定要看心理医生或精神科医生)。";
        } else {
            reportLevel = "*";
            content = content + "判断异常,前半部分总分为：" + underTotal;
        }

        map.put(UPPER_TOTAL, upperTotal);
        map.put(UNDER_TOTAL, underTotal);
        map.put(CONTENT, content);
        map.put(REPORT_LEVEL, reportLevel);
        return map;
    }
}
